<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'m8:machine:task:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="70%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <Tabs v-model:activeKey="activeKey" tabPosition="left">
      <Tabs.TabPane
        v-for="(item, index) in formTabs"
        :key="index"
        :forceRender="true"
        :tab="item.tabName"
      >
        <SingleForm
          v-if="flag"
          :schemas="item.colList"
          :formConfig="formConfig"
          :data="record"
          ref="singleFormArr"
        ></SingleForm>
      </Tabs.TabPane>
    </Tabs>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsTestTestDataForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { Tabs } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  // import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  // import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { TestData, testDataSave, testDataForm, formSet } from '/@/api/test/testData';
  // import { officeTreeData } from '/@/api/sys/office';
  // import { areaTreeData } from '/@/api/sys/area';
  // import { BasicUpload } from '/@/components/Upload';
  // import { WangEditor } from '/@/components/WangEditor';

  import SingleForm from './singleForm.vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('test.testData');
  const { showMessage } = useMessage();
  const record = ref<TestData>({} as TestData);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增数据') : t('编辑数据'),
  }));
  const singleFormArr = ref<any>(null);
  let formTabs = ref<any>([]);
  let formConfig = ref<any>({});

  let flag = ref(false);

  const activeKey = ref<number>(0);

  // const inputFormSchemas1: FormSchema[] = [
  //   {
  //     label: t('单行文本'),
  //     field: 'testInput',
  //     component: 'Input',
  //     componentProps: {
  //       maxlength: 200,
  //     },
  //     required: true,
  //   },
  //   // {
  //   //   field: 'testInputHelpMessage',
  //   //   component: 'Text',
  //   //   render: () => h('div', { class: 'ml-4 text-gray-500' }, '这是栅格帮助信息，优点是可以对齐。'),
  //   // },
  //   {
  //     label: t('多行文本'),
  //     field: 'testTextarea',
  //     component: 'InputTextArea',
  //     componentProps: {
  //       maxlength: 200,
  //     },
  //     // suffix: h('div', { class: 'ml-4 text-gray-500' }, 'Suffix帮助信息，优点是自由嵌入组件后。'),
  //     rules: [{ required: true }],
  //     colProps: { lg: 24, md: 24 },
  //   },
  //   {
  //     label: t('下拉框'),
  //     field: 'testSelect',
  //     component: 'Select',
  //     componentProps: {
  //       dictType: 'sys_menu_type',
  //       allowClear: true,
  //     },
  //   },
  //   {
  //     label: t('下拉多选'),
  //     field: 'testSelectMultiple',
  //     component: 'Select',
  //     componentProps: {
  //       dictType: 'sys_menu_type',
  //       allowClear: true,
  //       mode: 'multiple',
  //     },
  //   },
  //   {
  //     label: t('单选框'),
  //     field: 'testRadio',
  //     component: 'RadioGroup',
  //     componentProps: {
  //       dictType: 'sys_menu_type',
  //     },
  //   },
  //   {
  //     label: t('复选框'),
  //     field: 'testCheckbox',
  //     component: 'CheckboxGroup',
  //     componentProps: {
  //       dictType: 'sys_menu_type',
  //     },
  //   },
  //   {
  //     label: t('日期选择'),
  //     field: 'testDate',
  //     component: 'DatePicker',
  //     componentProps: {
  //       format: 'YYYY-MM-DD',
  //       showTime: false,
  //     },
  //   },
  //   {
  //     label: t('日期时间'),
  //     field: 'testDatetime',
  //     component: 'DatePicker',
  //     componentProps: {
  //       format: 'YYYY-MM-DD HH:mm',
  //       showTime: { format: 'HH:mm' },
  //     },
  //   },
  //   {
  //     label: t('用户选择'),
  //     field: 'testUser.userCode',
  //     fieldLabel: 'testUser.userName',
  //     component: 'TreeSelect',
  //     componentProps: {
  //       api: officeTreeData,
  //       params: { isLoadUser: true, userIdPrefix: '' },
  //       canSelectParent: false,
  //       allowClear: true,
  //     },
  //   },
  //   {
  //     label: t('用户列表选择'),
  //     field: 'testUser.userCode',
  //     component: 'ListSelect',
  //     componentProps: {
  //       selectType: 'empUserSelect',
  //     },
  //   },
  //   {
  //     label: t('机构选择'),
  //     field: 'testOffice.officeCode',
  //     fieldLabel: 'testOffice.officeName',
  //     component: 'TreeSelect',
  //     componentProps: {
  //       api: officeTreeData,
  //       allowClear: true,
  //     },
  //   },
  //   {
  //     label: t('区域选择'),
  //     field: 'testAreaCode',
  //     fieldLabel: 'testAreaName',
  //     component: 'TreeSelect',
  //     componentProps: {
  //       api: areaTreeData,
  //       allowClear: true,
  //     },
  //   },
  //   {
  //     label: t('备注信息'),
  //     field: 'remarks',
  //     component: 'InputTextArea',
  //     componentProps: {
  //       maxlength: 500,
  //     },
  //     slot: 'remarks',
  //     colProps: { lg: 24, md: 24 },
  //   },
  // ];
  // const inputFormSchemas2: FormSchema[] = [
  //   {
  //     label: t('图片上传'),
  //     field: 'dataMap',
  //     component: 'Upload',
  //     componentProps: {
  //       loadTime: computed(() => record.value.__t),
  //       bizKey: computed(() => record.value.id),
  //       bizType: 'testData_image',
  //       uploadType: 'image',
  //     },
  //     suffix: [
  //       h('div', { class: 'ml-4 text-gray-500' }, '请上传图片格式，文件小于 5 M。'),
  //       h('a', { href: 'https://jeesite.com', target: '_blank', class: 'mr-8' }, '查看模板'),
  //     ],
  //     colProps: { lg: 24, md: 24 },
  //   },
  //   {
  //     label: t('文件上传'),
  //     field: 'dataMap',
  //     component: 'Upload',
  //     componentProps: {
  //       loadTime: computed(() => record.value.__t),
  //       bizKey: computed(() => record.value.id),
  //       bizType: 'testData_file',
  //       uploadType: 'all',
  //     },
  //     suffix: [
  //       h('div', { class: 'ml-4 text-gray-500' }, '请上传文档格式，文件小于 5 M。'),
  //       h('a', { href: 'https://jeesite.com', target: '_blank', class: 'mr-8' }, '查看模板'),
  //     ],
  //     colProps: { lg: 24, md: 24 },
  //   },
  //   {
  //     label: t('子表数据'),
  //     field: 'testDataChildList',
  //     component: 'Input',
  //     colProps: { lg: 24, md: 24 },
  //     slot: 'testDataChildList',
  //   },
  // ];

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    flag.value = false;
    activeKey.value = 0;
    setDrawerProps({ loading: true });

    const res11 = await formSet({ viewCode: 'test_form001' });

    formTabs.value = res11.layVoucherView.formTabs;
    formConfig.value = res11.layVoucherView.formConfig;

    // await resetFields();
    const res = await testDataForm(data);
    record.value = (res.testData || {}) as TestData;
    record.value.__t = new Date().getTime();
    flag.value = true;
    // setFieldsValue(record.value);
    // setTestDataChildTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    let obj = {};
    let falg = false;
    await singleFormArr.value.forEach((item) => {
      // item.validateForm();
      item.validateForm().then((e) => {
        if (!e) {
          falg = true;
        } else {
          obj = { ...obj, ...e };
        }
      });
    });
    setTimeout(async () => {
      if (falg) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      } else {
        try {
          console.log(obj);
          setDrawerProps({ confirmLoading: true });
          const params: any = {
            isNewRecord: record.value.isNewRecord,
            id: record.value.id,
          };
          //   data.testDataChildList = await getTestDataChildList();
          const res = await testDataSave(params, obj);
          showMessage(res.message);
          setDrawerProps({ confirmLoading: false });
          setTimeout(closeDrawer);
          emit('success', obj);
        } catch (error: any) {
          // if (error && error.errorFields) {
          //   showMessage('您填写的信息有误，请根据提示修正。');
          // }
          console.log('error', error);
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }
    }, 0);
  }
</script>
